import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/no_more/no_more.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/community/community_date_model.dart';
import 'package:pornhub_app/utils/events.dart';

class ArroundCommunityPage extends StatefulWidget {
  final int userId;
  const ArroundCommunityPage({super.key, required this.userId});

  @override
  State<ArroundCommunityPage> createState() => _ArroundCommunityPageState();
}

class _ArroundCommunityPageState extends State<ArroundCommunityPage> {
  final _pageSize = 20;
  final PagingController<int, CommunityDateModel> _pagingController =
      PagingController(firstPageKey: 1);
  StreamSubscription? subscription;
  @override
  void initState() {
    super.initState();
    _pagingController.addPageRequestListener((pageKey) {
      initListData(pageKey);
    });
    subscription = eventBus.on<BloggerRefreshEvent>().listen((event) {
      if (event.tabName == "G圈") {
        _pagingController.refresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return PagedListView<int, CommunityDateModel>(
      pagingController: _pagingController,
      padding: EdgeInsets.only(top: 8.w),
      addAutomaticKeepAlives: true,
      physics: const ClampingScrollPhysics(),
      builderDelegate: PagedChildBuilderDelegate<CommunityDateModel>(
        noMoreItemsIndicatorBuilder: (context) => const NoMore(),
        noItemsFoundIndicatorBuilder: (context) => const NoData(),
        itemBuilder: (context, item, index) => Container(),
      ),
    );
  }

  Future initListData(int pageKey) async {
    List<CommunityDateModel> result =
        await httpInstance.get<CommunityDateModel>(
            url: 'community/dynamic/person/list',
            queryMap: {
              'status': 2,
              'userId': widget.userId,
              'page': pageKey,
              'pageSize': _pageSize,
            },
            complete: CommunityDateModel.fromJson);
    final isLastPage = result.length < _pageSize;
    if (isLastPage) {
      _pagingController.appendLastPage(result);
    } else {
      final nextPageKey = pageKey + 1;
      _pagingController.appendPage(result, nextPageKey as int?);
    }
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }
}
